package com.seehack.sample.springrest.httpclient.interceptor;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class AccessLogProcessor implements HttpProcessor {

    private static final Logger log = LoggerFactory.getLogger(AccessLogProcessor.class);
    private static final String X_START_TIME = "x-start-time";

    public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
        httpContext.setAttribute(X_START_TIME, System.currentTimeMillis());
    }

    public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
        String uri = "";
        // request
        final Object httpRequest = httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
        if (httpRequest instanceof HttpRequestWrapper) {
            HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) httpRequest;
            uri = httpRequestWrapper.getRequestLine().toString();
        }
        // end time
        long start = (Long) httpContext.getAttribute(X_START_TIME);
        long end = System.currentTimeMillis();
        // response status
        StatusLine statusLine = httpResponse.getStatusLine();
        log.info("uri: [{}] - response: [code: {}, reason: {}, cost: {}ms]",
                uri,
                statusLine.getStatusCode(),
                statusLine.getReasonPhrase(),
                end - start);
    }
}
